package fnic.prehand.action;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import fnic.jsontrans.AgentUrl;
import fnic.jsontrans.DeviceId;
import fnic.prehand.common.AgentConfig; 
import fnic.prehand.common.BlockQueueService;
import fnic.prehand.esagent.ap_measure_new2.APHTTPEsAgent;

@SuppressWarnings("serial")
public class APMsgServlet extends HttpServlet{
	private static final Logger LOG = Logger.getLogger(APMsgServlet.class);
	private static final AgentConfig config = AgentConfig.getInstance();
	
//	private static final String indexName=config.getAp_indexName();
//	private static final String apinfo_typeName=config.getAptype_apinfo();
//	private static final String stainfo_typeName=config.getAptype_stainfo();
//	private static final String aphistory_typeName=config.getAptype_apinfo_his();
//	private static final String approperty_typeName=config.getAptype_approperty();

	
//	private static final String APLOGIN = AgentUrl.ap_login;
//	private static final String APLOGOUT = "ap_logout";
//	private static final String APSEARCH = "ap_search/allapstatus";
//	private static final String STASEARCH = "ap_search/stastatus";
	
	private static final String SORTBY = "sortby";
	private static final String ORDER = "order";
	private static final String FROM = "from";
	private static final String SIZE = "size";
	private static final String APMAC = "apmac";
	private static final String STAMAC = "stamac";
	private static final String LEVELNUM = "levelnum";
	private static final String LEVELVALUE = "levelvalue";
//	private static final String RECENTDAY = "recentday";
	private static final String RECENTTIME = "recenttime";
	
	private final APHTTPEsAgent apesagent;
	public APMsgServlet(){
		apesagent = new APHTTPEsAgent();
	}
	
	@Override
	protected void doPost(HttpServletRequest request, 
			HttpServletResponse response) throws ServletException, IOException {
		String opt = request.getRequestURI();
		String httpbody = getHttpBody(request.getInputStream());
		boolean succeedfg = false;
		if(opt.equals(AgentUrl.APPROPERTY)){
			succeedfg = apesagent.dealApProperty(httpbody);
		}
		if(opt.equals(AgentUrl.APLOGIN)){
			succeedfg = apesagent.dealAPLog(httpbody, true);
		}else if(opt.equals(AgentUrl.APLOGOUT)){
			succeedfg = apesagent.dealAPLog(httpbody, false);
		}
		if(succeedfg){
			response.setStatus(HttpServletResponse.SC_OK);
		}else{
			LOG.error("ap http login/logout fail");
			response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
		}
	}
	
	@Override
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String opt = request.getRequestURI();
		
		
		
//		String apaggrfield = "ap_hotzone";
//		String staaggrfield = "sta_trace";
		String order = "desc";
		int from = 0;
		int size = 10;
		

		if(request.getParameter(ORDER)!=null){
			order = request.getParameter(ORDER);
		}
		if(request.getParameter(FROM)!=null){
			from = Integer.parseInt(request.getParameter(FROM));
		}
		if(request.getParameter(SIZE)!=null){
			size = Integer.parseInt(request.getParameter(SIZE));
		}
		boolean descfg;
		if(order.toLowerCase().equals("asc")){
			descfg = false;
		}else{
			descfg = true;
		}
		
		String searchRes;
		if(opt.equals(AgentUrl.APSEARCH)){
			String apsortfield = "ap_login";
			if(request.getParameter(SORTBY)!=null){
				 apsortfield = request.getParameter(SORTBY);
			}
			searchRes = apesagent.allAps(apsortfield, descfg, from, size);
		}else if(opt.equals(AgentUrl.STASEARCH)){
			String stasortfield = "sta_login";
			if(request.getParameter(SORTBY)!=null){
				 stasortfield = request.getParameter(SORTBY);
			}
			String apmac = request.getParameter(APMAC);
			searchRes = apesagent.stasByAp(apmac, stasortfield, descfg, from, size);
		}else if(opt.equals(AgentUrl.APAGGR)){
			searchRes = apesagent.apinfoLevelAggrgate(4);
		}else if(opt.equals(AgentUrl.STAAGGR)){
//			String staaggrsortfield = "num";
			int level = 0;
			String value = null;
			String stamac=null;
			if(request.getParameter(LEVELNUM)!=null){
				level = Integer.parseInt(request.getParameter(LEVELNUM));
			}
			if(request.getParameter(LEVELVALUE)!=null){
				value = request.getParameter(LEVELVALUE);
			}
			if(request.getParameter(STAMAC)!=null){
				stamac = request.getParameter(STAMAC);
			}
			if(request.getParameter(STAMAC)!=null){
				stamac = request.getParameter(STAMAC);
			}
//			if(request.getParameter(SORTBY)!=null){
//				 staaggrsortfield = request.getParameter(SORTBY);
//			}
			if(stamac==null){
				String staaggrsortfield = "ap_num";
				if(request.getParameter(SORTBY)!=null){
					staaggrsortfield = request.getParameter(SORTBY);
				}
				searchRes = apesagent.allStaHisAggr(level, value, staaggrsortfield, descfg, from, size);
			}else{
				searchRes = apesagent.singleStaHisAggr(stamac, level, value);
			}
		}
		else if(opt.equals(AgentUrl.CUSTOMAGGR)){
			String startday = null;
			int level = 0;
			String value = null;
			if(request.getParameter(LEVELNUM)!=null){
				level = Integer.parseInt(request.getParameter(LEVELNUM));
			}
			if(request.getParameter(LEVELVALUE)!=null){
				value = request.getParameter(LEVELVALUE);
			}
			if(request.getParameter(RECENTTIME)!=null){
				startday = request.getParameter(RECENTTIME);
			}
			
			searchRes = apesagent.customHisAggr(startday, level, value);
		}
		
		else if(opt.equals(AgentUrl.CUSTOMTYPEAGGR)){
			String startday=null;
			int level = 0;
			String value = null;
			if(request.getParameter(LEVELNUM)!=null){
				level = Integer.parseInt(request.getParameter(LEVELNUM));
			}
			if(request.getParameter(LEVELVALUE)!=null){
				value = request.getParameter(LEVELVALUE);
			}
			if(request.getParameter(RECENTTIME)!=null){
				startday = request.getParameter(RECENTTIME);
			}
			searchRes = apesagent.customTypeAggr(5*60, 16, startday, level, value);
		}

		else{
			LOG.error("get method url["+ opt +"] illegal");
			response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
			return;
		}
		
		PrintWriter pw = null;
		try {
			response.setContentType("application/json;charset=utf-8");
			response.setStatus(HttpServletResponse.SC_OK);
			pw = response.getWriter();
			pw.println(searchRes);
			pw.close();
		} catch (Exception e) {
			LOG.error("http rsp writer fail: " + e.getMessage());
			response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
		}
	}
	
	private String getHttpBody(InputStream stream){
		InputStreamReader isr = null;
		BufferedReader streamReader = null;
		StringBuilder probedata = null;
		String httpbody = null;
		boolean succeedfg = true;
		
		try {
			String tempString;
			isr = new InputStreamReader(stream, "UTF-8");
			streamReader = new BufferedReader(isr);
			probedata = new StringBuilder();
			while ((tempString = streamReader.readLine()) != null) {
				probedata.append(tempString);
			}
		} catch (Exception e) {
			LOG.warn("get httpbody exception - " + e.getMessage());
			succeedfg = false;
		} 
		if(succeedfg){
			httpbody = probedata.toString();
		}
		try {
			if (streamReader != null) {
				streamReader.close();
			}
			if (isr != null) {
				isr.close();
			}
		} catch (IOException e) {
			LOG.warn("close stream exception - " + e.getMessage());
		}
		LOG.info("http body:" + httpbody);
		return httpbody;
	}
}
